package route

import (
	"fmt"
	"os"
	"io"
	"alisms/model"
	"alisms/dal"
	"strings"
	"github.com/tealeg/xlsx"
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
)

type msg struct {
}
func (m msg) Sendmsg(ctx context.Context) {
	var op model.Ops
	ctx.ReadJSON(&op)
	srt := dal.Msg.Sendmsg(op.Rs, op.SignName, op.TemplateCode, op.Maps, op.Time)
	ctx.StatusCode(iris.StatusOK)
	ctx.JSON(map[string]interface{}{"success": "success", "srt": srt})
}
func (m msg) Upfile(ctx context.Context) {
	file, info, err := ctx.FormFile("uploadfile")
	if err != nil {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
		return
	}
	defer file.Close()
	fname := info.Filename
	// imgroute:="/images/"+fname
	// rt :=upimg(imgroute)
	 fmt.Println(fname)
	//创建一个具有相同名称的文件
	//假设你有一个名为'uploads'的文件夹
	//fmt.Print(fname)
	out, err := os.OpenFile("./data/"+fname,
		os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
		return
	}
	defer out.Close()
	io.Copy(out, file)
	
	
	 //strings.Replace(str03, "/", "**", -1)
	 rs,rt,tempstr,signstr,maps :=readdb("./data/"+fname)
	 fmt.Println(maps)
	 fmt.Println(rs)
	
	 ctx.StatusCode(iris.StatusOK)
	 ctx.JSON(map[string]interface{}{"success": rt == "success", "rt": rt, "rs": rs, "maps": maps,"tempstr":tempstr,"signstr":signstr})
}
func readdb(excel string) (rs []model.SmsN, rt string, tempstr, signstr string, maps []string) {
	xlFile, err := xlsx.OpenFile(excel)
	if err != nil {
		rt = "读取excel出错了"
		return
	}
	sht := xlFile.Sheets[0]
	sr := 0
	sc := 0
	lstr := ""
	flag := false
	cols := -1
	for _, row := range sht.Rows {

		if flag || sr > 12000 {
			break
		}
		sr++
		sc = 0
		if sr == 2 {
			continue
		}
		item := model.SmsN{}

		for _, cell := range row.Cells {
			if sc == cols || sc > 11 {
				break
			}
			str := cell.String()
			str = strings.TrimSpace(str)
			lstr = strings.ToLower(str)
			if sr == 1 {
				// 第一行，读取配置
				// 第一列，模板编号
				// 第二列，签名
				// 第三列，空
				// 第四列 直到colend
				if lstr == "colend" {
					cols = sc
					break
				}
				if sc == 0 && str != "" {
					tempstr = str
				}
				if sc == 1 && str != "" {
					signstr = str
				}
				if sc > 1 && sc < 12 && str != "" {
					maps = append(maps, str)
				}
			}

			if lstr == "rowend" {
				flag = true
				break
			}

			switch sc {
			case 0:
				item.BM = str
			case 1:
				item.Phone = str
			case 2:
				item.Col0 = str
			case 3:
				item.Col1 = str
			case 4:
				item.Col2 = str
			case 5:
				item.Col3 = str
			case 6:
				item.Col4 = str
			case 7:
				item.Col5 = str
			case 8:
				item.Col6 = str
			case 9:
				item.Col7 = str
			case 10:
				item.Col8 = str
			case 11:
				item.Col9 = str
			}
			sc++
		}
		if sr > 1 && !flag {
			rs = append(rs, item)
		}
	}
	rt = "success"
	return
}